package com.itany.corejava.code13_jdbc;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 石小俊
 * @date 2023年05月30日 10:17
 */
public class Test13_元数据 {

    public static void main(String[] args) throws DataAccessException {
//        selectAllEmp();
        insertReturnPrimaryKey(new User("test", "123456", "13812345678", "江苏-南京"));
    }

    public static void selectAll() throws DataAccessException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<User> users = new ArrayList<>();
        try {
            conn = JDBCUtil.getConnection();
            // 获取数据库的元数据
            // 通过连接可以获取到数据库的元数据
            DatabaseMetaData dbmd = conn.getMetaData();
            System.out.println("数据库产品名:" + dbmd.getDatabaseProductName());
            System.out.println("数据库版本号:" + dbmd.getDatabaseProductVersion());
            System.out.println("数据库驱动:" + dbmd.getDriverName());
            System.out.println("数据库驱动的版本号:" + dbmd.getDriverVersion());
            System.out.println("数据库的用户名:" + dbmd.getUserName());
            System.out.println("数据库URL地址:" + dbmd.getURL());

            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            // 通过结果集可以获取到结果集元数据
            ResultSetMetaData rsmd = rs.getMetaData();
            int count = rsmd.getColumnCount();
            System.out.println("结果集中共有:" + count + "列");
            for (int i = 1; i <= count; i++) {
                System.out.println("第" + i + "列的类型:" + rsmd.getColumnTypeName(i));
                System.out.println("第" + i + "列的类名:" + rsmd.getColumnName(i));
                System.out.println("第" + i + "列所在的表:" + rsmd.getTableName(i));
            }
        } catch (DataAccessException e) {
            throw e;
        } catch (SQLException e) {
            throw new DataAccessException("数据访问异常");
        } finally {
            JDBCUtil.close(conn, ps, rs);
        }
    }

    /**
     * 多对一查询
     * 查询所有员工以及对应员工所属的部门信息
     *
     * @return
     */
    public static List<Emp> selectAllEmp() throws DataAccessException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Emp> emps = new ArrayList<>();
        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append("select e.id,e.name,e.salary,d.id 'd.id',d.name 'd.name',d.remark ")
                    .append(" from t_emp e ")
                    .append(" left join t_dept d ")
                    .append("    on e.dept_id = d.id ")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            // 通过结果集可以获取到结果集元数据
            ResultSetMetaData rsmd = rs.getMetaData();
            int count = rsmd.getColumnCount();
            System.out.println("结果集中共有:" + count + "列");
            for (int i = 1; i <= count; i++) {
                System.out.println("第" + i + "列的类型:" + rsmd.getColumnTypeName(i));
                System.out.println("第" + i + "列的类名:" + rsmd.getColumnName(i));
                System.out.println("第" + i + "列所在的表:" + rsmd.getTableName(i));
            }
        } catch (DataAccessException e) {
            throw e;
        } catch (SQLException e) {
            throw new DataAccessException("数据访问异常");
        } finally {
            JDBCUtil.close(conn, ps, rs);
        }
        return emps;
    }

    public static Integer insertReturnPrimaryKey(User user) throws DataAccessException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Integer id = null;
        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user ")
                    .append("   (username,password,phone,address)")
                    .append(" values ")
                    .append("   (?,?,?,?)")
                    .toString();
            // 想要实现保存返回主键的功能
            // 在获取状态集的时候,需要设置状态集操作时保存返回主键
            // 存在第二个参数,用于设置保存是否返回自动生成的键的标志
            // 其值是由Statement提供的两个常量
            // RETURN_GENERATED_KEYS: 返回自动生成的键
            // NO_GENERATED_KEYS: 不返回自动生成的键
            // PreparedStatement是Statement的子类,可以继承对应的常量
            ps = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getPhone());
            ps.setString(4, user.getAddress());
            ps.executeUpdate();
            rs = ps.getGeneratedKeys();
            // 通过结果集可以获取到结果集元数据
            ResultSetMetaData rsmd = rs.getMetaData();
            int count = rsmd.getColumnCount();
            System.out.println("结果集中共有:" + count + "列");
            for (int i = 1; i <= count; i++) {
                // GENERATED_KEY
                System.out.println("第" + i + "列的类名:" + rsmd.getColumnName(i));
            }
            while (rs.next()) {
                id = rs.getInt(1);
            }
            return id;
        } catch (DataAccessException e) {
            throw e;
        } catch (SQLException e) {
            throw new DataAccessException("数据访问异常");
        } finally {
            JDBCUtil.close(conn, ps, rs);
        }
    }
}
